package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;


import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private final String name;

    private static final String KEY_PREFIX = "lock:";

    private final StringRedisTemplate stringRedisTemplate;

    public static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";

    public static final DefaultRedisScript<Long> unlock_script;

    static {
        unlock_script = new DefaultRedisScript<>();
        unlock_script.setLocation(new ClassPathResource("unlock.lua"));
        unlock_script.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public boolean tryLock(long timeoutSec) {
        String key = KEY_PREFIX + name;
        String value = ID_PREFIX + Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(key, value, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock() {
        // 获取锁
        // String value = ID_PREFIX + Thread.currentThread().getId();
        // String s = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        // if (value.equals(s)) {
        //     stringRedisTemplate.delete(KEY_PREFIX + name);
        // }
        //lua 脚本释放锁
        stringRedisTemplate.execute(unlock_script,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId());
    }
}
